package com.augurit.gzcgwsp.wfex.common.web;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.ExtBaseAction;
import com.augurit.common.base.extmodel.BasicCombo;
import com.augurit.common.base.form.ResultForm;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.lang.DateUtils;
import com.augurit.gzcgwsp.sendNotice.service.IExchangeStateService;
import com.augurit.gzcgwsp.ssgd.service.IYwRqSsgdSqbService;
import com.augurit.gzcgwsp.ssgd.web.form.YwRqSsgdSqbForm;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.web.form.WfActElemPrivDefForm;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.bi.web.form.WfPageElementForm;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfAction;
import com.augurit.wf.common.web.WfBusTemplateViewConfig;

@SuppressWarnings("serial")
@Results({
	@Result(name = WfEXAction.YSL_DRAF, location = "/gzcgwsp/wfex/client/common/wf-ysl-draft.jsp"),
	@Result(name = WfEXAction.SMART_YSL_DRAF, location = "/gzcgwsp/wfex/client/common/wf-ysl-draft-sf.jsp"),
	@Result(name = WfEXAction.OPINION, location = "/gzcgwsp/wfex/client/common/wf-opinion.jsp"),
	@Result(name = WfEXAction.SIGN_TASK, location = "/gzcgwsp/wfex/client/common/wf-sign-task.jsp"),
	@Result(name = WfEXAction.SMART_SIGN_TASK, location = "/gzcgwsp/wfex/client/common/wf-sign-task-sf.jsp"),
	@Result(name = WfEXAction.SMART_DRAFT, location = "/gzcgwsp/wfex/client/common/wf-draft-sf.jsp"),
	@Result(name = WfEXAction.DRAFT, location = "/gzcgwsp/wfex/client/common/wf-draft.jsp"),
	@Result(name = WfEXAction.VIEW_TASK, location = "/gzcgwsp/wfex/client/common/wf-view-task.jsp"),
	@Result(name = WfEXAction.SMART_VIEW_TASK, location = "/gzcgwsp/wfex/client/common/wf-view-task-sf.jsp")
})
public class WfEXAction extends WfAction{
	private static final Logger log=Logger.getLogger(WfEXAction.class);
	public static final String YSL_DRAF = "ysl-draft";			//预受理页面
	public static final String SMART_YSL_DRAF = "smart-ysl-draft";			//预受理页面
	public static final String OPINION = "opinion";			//意见页面sign-task
	public static final String SIGN_TASK = "sign-task";			//意见页面
	public static final String SMART_SIGN_TASK = "smart-sign-task";  //智能表单意见页面
	public static final String DRAFT = "draft";
	public static final String SMART_DRAFT = "smart-draft";   //智能表单草拟
	public static final String VIEW_TASK = "view-task";
	public static final String SMART_VIEW_TASK = "smart-view-task";
	
	@Autowired
	private IWfBusTemplateService wfBusTemplateService;	
	@Autowired
	private IWfService wfService;	
	@Autowired
	private IWfServiceEX wfServiceEX;
	@Autowired
	private IWfBusTemplateServiceEX wfBusTemplateServiceEX;	
	@Autowired
	private IYwRqSsgdSqbService ywRqSsgdSqbService;	
	@Autowired
	private IExchangeStateService exchangeStateService;
	
	//属性
	private Page page = new Page();
	
	private WfBusTemplateForm template = new WfBusTemplateForm();
	private WfBusInstanceTaskForm instance = new WfBusInstanceTaskForm();
	private Long[] taskInstDbids;	//用于批量签收

	private WfBusTemplateViewConfig viewConfig;
	
	private WfPageElementForm pageElement = new WfPageElementForm();
	
	private String loadProcessDiagramUrl;		//加载流程图的url
	
	private String forward;
	
	
	/**
	 * 判断是否是智能表单生成的表单页面
	 * @param templateCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private boolean isSmartForm(String templateCode){
		boolean result = false;
		List list = wfBusTemplateService.getElementsByType(templateCode, WfPageElementForm.FORM_ELEM_TYPE, false);
		if(list != null && list.size() >1)
			result = true;
		
		return result;
	}

	
	/**
	 * 收案  方法
	 * @return
	 * @throws Exception
	 */
	public String wfDraft() throws Exception {
		template = wfBusTemplateService.getByTemplateCode(template.getTemplateCode());
		
		String wfDefId = WfUtils.convertToProcessDefinitionId(template.getWfDefKey(), template.getWfDefVersion());
		instance.setActivityName(wfService.getStartTaskActivityName(wfDefId));
		
		//设置流程定义ID
		instance.setProcessDefId(wfDefId);
		
		//设置流程实体的版本
		instance.setVersion(template.getWfDefVersion());
		
		////////////判断是否是智能表单生成的多表单///////////
		if(isSmartForm(template.getTemplateCode()))
			return getForward("smart-draft");
		//////////

		return getForward("draft");
		
	}
	
	/**
	 * 获取登录用户的呈批业务,用于查询待办已办的查询
	 * @return
	 */
	public String getCpyws(){
		 LoginUserForm loginUserForm = this.getLoginUser();
		 List<WfBusTemplateForm> AllList = wfBusTemplateServiceEX.getAllActive(loginUserForm);
    	 List<BasicCombo> combos = new ArrayList<BasicCombo>();
    	 if(AllList != null){
    		 for (WfBusTemplateForm tplForm : AllList) {
 				BasicCombo combo = new BasicCombo();
 				combo.setLabel(tplForm.getTemplateName());
 				combo.setValue(tplForm.getTemplateName() + "");
 				combos.add(combo);
	 		 }
	 		 ExtBaseAction.extRenderListJson(combos, true);
    	 }		 
		return null;
	}
	
	/**
	 * 预受理 方法
	 * @return
	 * @throws Exception
	 */
	public String wfYslDraft() throws Exception {
		String busEntityKey = this.getRequest().getParameter("id");
		String tplcode = this.getRequest().getParameter("templateCode");
		
        template = wfBusTemplateService.getByTemplateCode(tplcode);
        
        String wfDefId = WfUtils.convertToProcessDefinitionId(template.getWfDefKey(), template.getWfDefVersion());
        instance.setActivityName(wfService.getStartTaskActivityName(wfDefId));
        
        //设置流程实体的版本
        instance.setVersion(template.getWfDefVersion());
        BaseAction.getRequest().setAttribute("busEntityKey", busEntityKey);
        
        ////////////判断是否是智能表单生成的多表单///////////
		if(isSmartForm(template.getTemplateCode()))
			return getForward("smart-ysl-draft");
		//////////
		return getForward("ysl-draft");
		
	}
	
	/**
	 * 获取TaskOpinWin,加载jsp为了满足拖拉效果
	 */
	public String getTaskOpinionWin() throws Exception{
		if(instance != null && instance.getTaskInstDbid() != null)
			return getForward("opinion");
		return null;
	}
	
	/**
	 * 发送 方法
	 * @return
	 * @throws Exception
	 */
	public String wfSend() throws Exception {
		LoginUserForm user = this.getLoginUser();
		//先检测选择用户是否正确
		ResultForm result =this.wfServiceEX.wfSend(instance, user);
		renderJson(result);
		return null;
	}
	
	/**
	 * 点击补交受理按钮，保存补交受理信息到政务中心表
	 */
	public void saveBjslByButton(){
		String procInstId=getRequest().getParameter("procInstId");
		String taskInstDbid=getRequest().getParameter("taskInstDbid");
		String templateCode=getRequest().getParameter("templateCode");
		String masterEntityKey=getRequest().getParameter("masterEntityKey");
		System.out.println("procInstId = "+procInstId);
		System.out.println("taskInstDbid = "+taskInstDbid);
		System.out.println("templateCode = "+templateCode);
		System.out.println("masterEntityKey = "+masterEntityKey);
		String durationExpression = wfServiceEX.getProcDueExpressIonByTaskInstDbid(Long.parseLong(taskInstDbid));
		LoginUserForm user = this.getLoginUser();
		//点击补交受理按钮，保存补交受理
		Locale locale = Locale.getDefault(); 
		ResourceBundle localResource = ResourceBundle.getBundle("interfaceExchange", locale); 
		String sxbm = wfServiceEX.getPropertiesValueByKey(localResource, templateCode);
		boolean flag = exchangeStateService.saveBjsl(user, procInstId, Long.parseLong(taskInstDbid), templateCode, masterEntityKey, sxbm,durationExpression);
		System.out.println("flag = "+flag);
		this.renderJson(new ResultForm(flag,""));
	}
	
	/**
	 * 检查补交数据
	 * @return
	 * @throws Exception
	 */
	public String checkBjData() throws Exception{
		String templteCode=getRequest().getParameter("templateCode");
		String masterEntityKey=getRequest().getParameter("masterEntityKey");
		boolean flag=wfServiceEX.checkBjData(templteCode,masterEntityKey);
		if(flag){
			this.getResponse().getWriter().print("notbjclqd");
		}else{
			this.getResponse().getWriter().print("true");

		}
		return null;
	}
	
	/**
	 * 检查是否已经保存了补交受理表单
	 * @return
	 * @throws Exception
	 */
	public String checkBjslsjByTemplateCodeAndYwId() throws Exception{
		String templteCode=getRequest().getParameter("templateCode");
		String masterEntityKey=getRequest().getParameter("masterEntityKey");
		boolean flag=wfServiceEX.checkBjslsjByTemplateCodeAndYwId(templteCode,masterEntityKey);
		if(flag){
			this.getResponse().getWriter().print("exist");
		}else{
			this.getResponse().getWriter().print("notExist");

		}
		return null;
	}
	
	/**
	 * 待办  方法
	 * @return
	 * @throws Exception
	 */
	public String signTask() throws Exception {
		instance = wfService.getWfBusInstanceTaskById(instance.getTaskInstDbid(), this.getLoginUserName());
		instance.setViewName(WfActElemPrivDefForm.DB_ZB_VIEW);
		
		////////////判断是否是智能表单生成的多表单///////////
		if(isSmartForm(instance.getTemplateCode()))
			return getForward("smart-sign-task");
		//////////

		return getForward("sign-task");
	}
	
	/**
	 * 已办、办结  方法
	 * @return
	 * @throws Exception
	 */
	public String viewTask() throws Exception {
		String viewName = instance.getViewName();
		instance = wfService.getWfBusInstanceById(instance.getWfBusInstanceId());
		instance.setVersion(wfService.getProcDefByProcInstId(instance.getProcInstId()).getVersion());
		instance.setViewName(viewName);
		instance.setActivityName(null);
		
		////////////判断是否是智能表单生成的多表单///////////
		if(isSmartForm(instance.getTemplateCode()))
			return getForward("smart-view-task");
		//////////
		return getForward("view-task");
	}
	
	public String showWfSendWin() throws Exception {
		wfService.loadWfSendOption(instance);
		
		if(instance.isDirectSend())
			wfSend();

		this.renderJson(new ResultForm(false, instance));	//false表示不是直接发送，需要用户人工发送
		return null;
	}
	
	private String getForward(String defaultForward){
		if(forward != null && forward.trim().length() > 0)
			return forward;
		else
			return defaultForward;
	}
	
	public String getForward() {
		return forward;
	}

	public void setForward(String forward) {
		this.forward = forward;
	}
	public WfPageElementForm getPageElement() {
		return pageElement;
	}

	public void setPageElement(WfPageElementForm pageElement) {
		this.pageElement = pageElement;
	}

	public WfBusInstanceTaskForm getInstance() {
		return instance;
	}
	
	public void setInstance(WfBusInstanceTaskForm instance) {
		this.instance = instance;
	}
	
	public WfBusTemplateForm getTemplate() {
		return template;
	}

	public void setTemplate(WfBusTemplateForm template) {
		this.template = template;
	}

	public WfBusTemplateViewConfig getViewConfig() {
		return viewConfig;
	}

	public void setViewConfig(WfBusTemplateViewConfig viewConfig) {
		this.viewConfig = viewConfig;
	}

	public Long[] getTaskInstDbids() {
		return taskInstDbids;
	}

	public void setTaskInstDbids(Long[] taskInstDbids) {
		this.taskInstDbids = taskInstDbids;
	}
	
	public String getLoadProcessDiagramUrl() {
		return loadProcessDiagramUrl;
	}
	
	public void setLoadProcessDiagramUrl(String loadProcessDiagramUrl) {
		this.loadProcessDiagramUrl = loadProcessDiagramUrl;
	}
	
	/**
     * 改变公示状态
     * @return
     * @throws Exception
     */
	public void changeIsAjgsById(){
		String idTemp = super.getParameter("id");
		String state = super.getParameter("state");
		String taskInstDbid = super.getParameter("taskInstDbid");
		Date date = new Date();
		Long id = Long.parseLong(idTemp);
		System.out.println("id ============== "+id);
		//计算七天后，案件自动结束公示时间
		//读取接口配置信息  公示时间
		Locale locale = Locale.getDefault(); 
		ResourceBundle localResource = ResourceBundle.getBundle("interfaceExchange", locale); 
		String gssjStr = localResource.getString("gssj");//7 business days
		String gssj = (String)(gssjStr.split(" ")[0]);
        Date endDate = wfServiceEX.calculateDueDate(date, gssjStr);
//        String aa = DateUtils.dateTimeToString(endDate, DateUtils.YEAR_MOUTH_DAY_);
        //viewEndDate是页面上显示的【公示结束时间】     
        //endDate是定时器调用的【公示结束时间】   endDate比viewEndDate大一天
        Date viewEndDate = endDate;
        Calendar calendar=Calendar.getInstance();   //创建一个日历对象
        calendar.setTime(viewEndDate);             //用当前时间初始化日历时间
        calendar.add(calendar.DATE, -1);
        viewEndDate = calendar.getTime();
		boolean flag = ywRqSsgdSqbService.changeIsAjgsById(state,id,date,viewEndDate);
		System.out.println("flag = "+flag);
		if(flag == true){
			YwRqSsgdSqbForm form = ywRqSsgdSqbService.get(id);	
			form.setId(id);
			if(StringUtils.isNotEmpty(state) && "1".equals(state)){//启动公示时，则
				try {
					wfServiceEX.startPublic(form,Long.parseLong(taskInstDbid),instance,this.getLoginUser(),endDate,gssj);
				} catch (Exception e) {
					flag = false;
					form.setIsAjgs(null);
					ywRqSsgdSqbService.save(form);
				}
			}else if(StringUtils.isNotEmpty(state) && "0".equals(state)){//结束公示，则把记录保存起来，通过定时器调用方欣的案件公示webservice接口
				try {
					wfServiceEX.stopPublic(form.getAcceptNo(),form.getApprovalNo());
				} catch (Exception e) {
					flag = false;
					form.setIsAjgs("1");
					ywRqSsgdSqbService.save(form);
				}
			}			
			String returnDate = DateUtils.dateTimeToString(viewEndDate, DateUtils.YEAR_MOUTH_DAY_);
			this.renderJson(new ResultForm(flag,returnDate));
		}else{
			this.renderJson(new ResultForm(flag,""));
		}
		
	}
	
	
	
	
}
